package com.cheng.spider.extract.binary;

import com.cheng.spider.constant.MimeType;
import com.cheng.spider.extract.DataResolver;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public abstract class BinaryDataResolver implements DataResolver {

    private static final Logger LOGGER = LoggerFactory.getLogger(BinaryDataResolver.class);

    private FileNameGenerator fileNameGenerator;

    private String savePath;

    public BinaryDataResolver() {
        fileNameGenerator = initFileNameGenerator();
        savePath = initSavePath();
    }

    @Override
    public void resolve(HttpResponse response, MimeType mimeType) {

        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        String fileName = null;
        File file = null;
        try {
            fileName = fileNameGenerator.generateName() + "." + mimeType.getExtendName();
            file = new File(savePath + fileName);
            LOGGER.info("写入文件：" + savePath + File.separator + fileName);
            LOGGER.info("实际路径：" + file.getAbsolutePath());
            if (!file.exists()) {
                file.createNewFile();
            }
            inputStream = response.getEntity().getContent();
            fileOutputStream = new FileOutputStream(file);
            int b;
            while ((b = inputStream.read()) != -1) {
                fileOutputStream.write(b);
            }
            fileOutputStream.flush();
        } catch (IOException e) {
            LOGGER.error("写入文件出错！");
            e.printStackTrace();
        } finally {
            if (inputStream != null)
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (fileOutputStream != null)
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

    protected abstract FileNameGenerator initFileNameGenerator();

    protected abstract String initSavePath();
}
